import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chewie/chewie.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/commuity/MaterialCenter.dart';
import 'package:panda/entity/gallery_entity.dart';
import 'package:panda/event/ShopCarEvent.dart';
import 'package:panda/goods/ShareGoodsPic.dart';
import 'package:panda/goods/sku_dialog.dart';
import 'package:panda/home/MyShopCar.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/jiayouzhan/KefuTalk.dart';
import 'package:panda/login/Welcome.dart';
import 'package:panda/order/OrderPage.dart';
import 'package:panda/order/OrderPay.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';

import 'BuyGoods.dart';
import 'GoodsDetailsModel.dart';
import 'SkuProvider.dart';

class GoodsDetail2Page extends StatefulWidget {
  String goods_id = "";
  String img, zero;
  int buyNow = 0;
  int type = 0; //默认非抢购
  String id = "0";

  String start_time = "",
      end_time = "",
      limit_num = "",
      all_num = "",
      sale_num = "";
  GoodsDetail2Page(
      {Key key,
      @required this.goods_id,
      @required this.img,
      this.type,
      this.id,
      this.buyNow,
      this.all_num,
      this.zero,
      this.end_time,
      this.limit_num,
      this.sale_num,
      this.start_time})
      : super(key: key);

  _GoodsDetail2PageState createState() => _GoodsDetail2PageState();
}

class _GoodsDetail2PageState extends State<GoodsDetail2Page> {
  double appBarAlpha = 0;
  SkuProvider skuProvider;
  Object price = "";
  bool isCheck = true;
  Object old_price = "";
  String goods_name = "", lv_price = "";
  String sales_num = "0";
  String all_num = "0";
  String html = "";
  String freight = "";
  List<GalleryModel> gallery = List();
  bool hasSku = false;
  int count = 0;
  int goods_num = 1;
  String token = "", video = "", uid = "";
  Map<String, dynamic> skuMap = {"skus": [], "goods": []};
  GoodsDetailsModel goodsDetailsModel;
  Timer _timerIndex;
  String _day1 = '';
  String _hour1 = '';
  String _minute1 = '';
  String _second1 = '', desc = "";
  bool play = false;
  ChewieController chewieController;
  VideoPlayerController videoPlayerController;
  _onScroll(offset) {
    double alpha = offset / 50;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      getGoodsDetail();
    });
    getBoolean("isCheck").then((value) {
      isCheck = value;
    });
    // if (widget.type == 1) {

    // }
    GalleryModel model = new GalleryModel(img: "");
    gallery.add(model);
    count = 1;
    goodsDetailsModel = GoodsDetailsModel.fromJson(skuMap);
    skuProvider = SkuProvider(goodsDetailsModel);
    var list =
        goodsDetailsModel.goods.map((item) => item.attribute_name).toList();
    skuProvider.selectedSku = "请选择\t${list.join("，")}";
  }

  getGoodsDetail() async {
    Map map = new Map();
    map['goods_id'] = widget.goods_id;
    map['token'] = APPLIC.userInfoMap == null ? "" : token;
    map['sign_type'] = SignType.GET_GOODS_DETAIL;
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_DETAIL, data: getSign(map));
    print(response);
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      gallery.clear();
      if (userMap['data']['imglist'] == null ||
          (userMap['data']['imglist'] as List).length == 0) {
        GalleryModel model =
            new GalleryModel(img: userMap['data']['goodsMsg']['img']);
        gallery.add(model);
      } else {
        (userMap['data']['imglist'] as List).forEach((v) {
          gallery.add(new GalleryModel.fromJson(v));
        });
      }
      setState(() {
        count = gallery.length;
      });
      setState(() {
        _timeFunc(userMap['data']['goodsMsg']['end_time']);
        html = userMap['data']['goodsMsg']['content'] == null
            ? ""
            : userMap['data']['goodsMsg']['content'];
        goods_name = userMap['data']['goodsMsg']['goods_name'];
        sales_num = (int.parse(
                    userMap['data']['goodsMsg']['virtual_volume'].toString()) +
                int.parse(
                    userMap['data']['goodsMsg']['sales_volume'].toString()))
            .toString();
        price = userMap['data']['goodsMsg']['price'];
        all_num = userMap['data']['goodsMsg']['num'].toString();
        freight = userMap['data']['goodsMsg']['freight'];
        old_price = userMap['data']['goodsMsg']['old_price'];
        video = userMap['data']['goodsMsg']['goods_code'];
        if (video != null &&
            video != "" &&
            video != "null" &&
            video.length > 20) {
          count = count + 1;
          videoPlayerController = VideoPlayerController.network(video);
          chewieController = ChewieController(
            videoPlayerController: videoPlayerController,
            aspectRatio: 1 / 1,
            autoInitialize: true,
            autoPlay: false,
            looping: false,
          );
          if (chewieController != null && videoPlayerController != null) {
            chewieController.play();
            chewieController.pause();
          }
        }
        lv_price = userMap['data']['goodsMsg']['lv_price'].toString();
        desc = userMap['data']['goodsMsg']['description'].toString();
        // print(userMap['data']['goodsMsg']['sku_arr'] ?? "");
        // print((userMap['data']['skulist'].toString()) ?? "");
        if (userMap['data']['skulist'] != null &&
            (userMap['data']['skulist'] as List).length > 0) {
          setState(() {
            hasSku = false;
            skuMap['skus'] = userMap['data']['skulist'];
            skuMap['goods'] = userMap['data']['goodsMsg']['sku_arr'];
            goodsDetailsModel = GoodsDetailsModel.fromJson(skuMap);
            skuProvider = SkuProvider(goodsDetailsModel);
            var list = goodsDetailsModel.goods
                .map((item) => item.attribute_name)
                .toList();
            skuProvider.selectedSku = "请选择\t${list.join("，")}";
          });
          // if (widget.buyNow == 1) {
          //   showGoodsAttributes(context);
          // }
        } else {
          setState(() {
            hasSku = true;
          });
        }
        showGoodsAttributes(context);
      });
    } else {
      Fluttertoast.showToast(msg: userMap['msg']);
    }
  }

  void _timeFunc(time) {
    var _newDate = DateTime.now();
    const period = const Duration(seconds: 1);
    var _diffDate = DateTime.parse(time.toString());
    _timerIndex = Timer.periodic(period, (timer) {
      //到时回调
      _diffDate = _diffDate.subtract(Duration(seconds: 1));
      // count++;
      if (_diffDate.difference(_newDate).inSeconds <= 0) {
        //取消定时器，避免无限回调
        timer.cancel();
        timer = null;
      }
      // print();
      var _surplus = _diffDate.difference(_newDate);
      int _day = (_surplus.inSeconds ~/ 3600) ~/ 24;
      int hour = (_surplus.inSeconds ~/ 3600) % 24;
      int minute = _surplus.inSeconds % 3600 ~/ 60;
      int second = _surplus.inSeconds % 60;
      // formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second);
      setState(() {
        _day1 = _day.toString() ?? '0';
        _hour1 = hour.toString() ?? '0';
        _minute1 = minute.toString() ?? '0';
        _second1 = second.toString() ?? '0';
        _day1 = _day1.length > 1 ? _day1 : ("0" + _day1);
        _hour1 = _hour1.length > 1 ? _hour1 : ("0" + _hour1);
        _minute1 = _minute1.length > 1 ? _minute1 : ("0" + _minute1);
        _second1 = _second1.length > 1 ? _second1 : ("0" + _second1);
        // _text = _diffDate.weekday.toString()+'  ' +_diffDate.hour.toString()+':' + _diffDate.minute.toString() +':'+ _diffDate.second.toString();
      });
      // debugPrint(_text);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (videoPlayerController != null) {
      videoPlayerController.dispose();
      chewieController.dispose();
    }
    if (widget.type != null) _timerIndex.cancel();
    _timerIndex = null;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text('重选商品规格',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: ChangeNotifierProvider.value(
          value: skuProvider,
          child: Consumer<SkuProvider>(builder: (context, provider, _) {
            return new Column(
              children: <Widget>[
                Expanded(
                  child: Container(
                      child: new Scrollbar(
                    child: new SingleChildScrollView(
                      child: new Container(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Stack(
                              children: <Widget>[
                                Container(
                                  height: MediaQuery.of(context).size.width,
                                  child: Swiper(
                                    containerHeight:
                                        MediaQuery.of(context).size.width,
                                    itemHeight:
                                        MediaQuery.of(context).size.width,
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      if (video != null &&
                                          video != "" &&
                                          video.length > 20 &&
                                          video != "null" &&
                                          index == 0) {
                                        return Stack(
                                          children: <Widget>[
                                            Chewie(
                                              controller: chewieController,
                                            ),
                                            Positioned(
                                              child: Offstage(
                                                offstage: play,
                                                child: GestureDetector(
                                                  child: Icon(
                                                    Icons.play_circle_outline,
                                                    color: mainColor,
                                                    size: 60,
                                                  ),
                                                  onTap: () {
                                                    play = true;
                                                    chewieController.play();
                                                    setState(() {});
                                                  },
                                                ),
                                              ),
                                              left: (MediaQuery.of(context)
                                                          .size
                                                          .width -
                                                      60) /
                                                  2,
                                              top: (MediaQuery.of(context)
                                                          .size
                                                          .width -
                                                      60) /
                                                  2,
                                            )
                                          ],
                                        );
                                      }
                                      if (video != null &&
                                          video != "" &&
                                          video.length > 20 &&
                                          video != "null") {
                                        index = index - 1;
                                      }
                                      return new ClipRRect(
                                        child: gallery[index].img == ""
                                            ? SizedBox()
                                            : gallery[index]
                                                    .img
                                                    .contains("upload")
                                                ? CachedNetworkImage(
                                                    imageUrl: gallery[index]
                                                            .img
                                                            .contains("http")
                                                        ? gallery[index].img
                                                        : Api.BaseUrl +
                                                            gallery[index].img,
                                                    fit: BoxFit.fill,
                                                  )
                                                : CachedNetworkImage(
                                                    imageUrl: gallery[index]
                                                            .img
                                                            .contains("http")
                                                        ? gallery[index].img
                                                        : Api.ImgBaseUrl +
                                                            gallery[index].img,
                                                    fit: BoxFit.fill,
                                                  ),
                                        borderRadius:
                                            BorderRadius.circular(0.0),
                                      );
                                    },
                                    onIndexChanged: (index) {
                                      if (chewieController != null) {
                                        // if (index == 0&&!play) {
                                        //   chewieController.play();
                                        // } else {
                                        play = false;
                                        chewieController.pause();
                                        setState(() {});
                                        //   }
                                      }
                                    },
                                    itemCount: count,
                                    pagination: new SwiperPagination(
                                        builder: DotSwiperPaginationBuilder(
                                            color: Colors.grey,
                                            activeColor: mainColor,
                                            size: 7.0,
                                            activeSize: 7.0)),
                                    scrollDirection: Axis.horizontal,
                                    autoplay: false,
                                    onTap: (index) {
                                      // Navigator.of(context)
                                      //     .push(new MaterialPageRoute(builder: (context) {
                                      //   return new HomeWebview(
                                      //     article_id: bannerData[index].img,
                                      //     title: bannerData[index].title,
                                      //   );
                                      // }));
                                    },
                                  ),
                                ),
                              ],
                            ),
                            Container(
                                width: MediaQuery.of(context).size.width,
                                color: Color(0xff333333),
                                padding: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(20),
                                    ScreenUtil.getInstance().setHeight(20),
                                    ScreenUtil.getInstance().setHeight(20),
                                    (ScreenUtil.getInstance().setHeight(20))),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                        child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: <Widget>[
                                            Text(MONEY,
                                                style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(
                                                              SMALL_FONT_SIZE +
                                                                  2),
                                                  color: white,
                                                )),
                                            Text(price,
                                                style: TextStyle(
                                                  fontSize:
                                                      ScreenUtil.getInstance()
                                                          .setSp(42),
                                                  color: white,
                                                )),
                                          ],
                                        ),
                                        Container(height: 2),
                                        Row(children: <Widget>[
                                          Text("市场价" + old_price.toString(),
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(26),
                                                color: Colors.grey,
                                              )),
                                          Container(width: 8),
                                          Text('销量:$sales_num 件',
                                              textAlign: TextAlign.right,
                                              style: TextStyle(
                                                fontSize: ScreenUtil
                                                        .getInstance()
                                                    .setSp(SMALL_FONT_SIZE + 2),
                                                color: mainColor,
                                              ))
                                        ]),
                                      ],
                                    )),
                                    Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.end,
                                        children: <Widget>[
                                          Text("距离活动结束",
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            MINI_FONT_SIZE + 2),
                                                color: white,
                                              )),
                                          Container(
                                              padding: EdgeInsets.only(top: 5),
                                              child: Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.end,
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.end,
                                                  children: <Widget>[
                                                    // Container(
                                                    //   padding:
                                                    //       EdgeInsets
                                                    //           .all(2),
                                                    //   decoration: BoxDecoration(
                                                    //       color: mainColor,
                                                    //       borderRadius:
                                                    //           BorderRadius.circular(
                                                    //               3)),
                                                    //   child: Text(
                                                    //       _day1,
                                                    //       style:
                                                    //           TextStyle(
                                                    //         fontSize: ScreenUtil
                                                    //                 .getInstance()
                                                    //             .setSp(
                                                    //                 MINI_FONT_SIZE),
                                                    //         color:
                                                    //             white,
                                                    //       )),
                                                    // ),
                                                    // Padding(
                                                    //   padding: EdgeInsets
                                                    //       .only(
                                                    //           left: 3,
                                                    //           right:
                                                    //               3),
                                                    //   child: Text("天",
                                                    //       style:
                                                    //           TextStyle(
                                                    //         fontSize: ScreenUtil
                                                    //                 .getInstance()
                                                    //             .setSp(
                                                    //                 MINI_FONT_SIZE),
                                                    //         color:
                                                    //             white,
                                                    //       )),
                                                    // ),
                                                    Container(
                                                      padding:
                                                          EdgeInsets.all(4),
                                                      decoration: BoxDecoration(
                                                          color: mainColor,
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(3)),
                                                      child: Text(_hour1,
                                                          style: TextStyle(
                                                            fontSize: ScreenUtil
                                                                    .getInstance()
                                                                .setSp(
                                                                    MINI_FONT_SIZE),
                                                            color: white,
                                                          )),
                                                    ),
                                                    Padding(
                                                      padding:
                                                          EdgeInsets.all(3),
                                                      child: Text(":",
                                                          style: TextStyle(
                                                            fontSize: ScreenUtil
                                                                    .getInstance()
                                                                .setSp(
                                                                    MINI_FONT_SIZE),
                                                            color: mainColor,
                                                          )),
                                                    ),
                                                    Container(
                                                      padding:
                                                          EdgeInsets.all(4),
                                                      decoration: BoxDecoration(
                                                          color: mainColor,
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(3)),
                                                      child: Text(_minute1,
                                                          style: TextStyle(
                                                            fontSize: ScreenUtil
                                                                    .getInstance()
                                                                .setSp(
                                                                    MINI_FONT_SIZE),
                                                            color: white,
                                                          )),
                                                    ),
                                                    Padding(
                                                      padding:
                                                          EdgeInsets.all(3),
                                                      child: Text(":",
                                                          style: TextStyle(
                                                            fontSize: ScreenUtil
                                                                    .getInstance()
                                                                .setSp(
                                                                    MINI_FONT_SIZE),
                                                            color: mainColor,
                                                          )),
                                                    ),
                                                    Container(
                                                      padding:
                                                          EdgeInsets.all(4),
                                                      decoration: BoxDecoration(
                                                          color: mainColor,
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(3)),
                                                      child: Text(_second1,
                                                          style: TextStyle(
                                                            fontSize: ScreenUtil
                                                                    .getInstance()
                                                                .setSp(
                                                                    MINI_FONT_SIZE),
                                                            color: white,
                                                          )),
                                                    ),
                                                  ]))
                                        ])
                                  ],
                                )),
                            Container(
                                color: white,
                                margin: EdgeInsets.only(top: 10),
                                alignment: Alignment.centerLeft,
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                        child: Padding(
                                      padding:
                                          EdgeInsets.fromLTRB(5, 10, 10, 15),
                                      child: Text(goods_name,
                                          style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE),
                                            fontWeight: FontWeight.bold,
                                            color: black,
                                          )),
                                    )),
                                    GestureDetector(
                                        onTap: () {
                                          Navigator.of(context).push(
                                              new MaterialPageRoute(
                                                  builder: (context) {
                                            return new MaterialCenterPage(
                                              type: 0,
                                            );
                                          }));
                                        },
                                        behavior: HitTestBehavior.opaque,
                                        child: Padding(
                                            padding: EdgeInsets.fromLTRB(
                                                10, 5, 15, 5),
                                            child: new Column(
                                              children: <Widget>[
                                                Padding(
                                                  padding: EdgeInsets.all(3),
                                                  child: Image.asset(
                                                      'images/icon_nav_share.png',
                                                      scale: 1.7),
                                                ),
                                                Text('素材',
                                                    style: TextStyle(
                                                        fontSize: ScreenUtil
                                                                .getInstance()
                                                            .setSp(
                                                                SMALL_FONT_SIZE -
                                                                    4)))
                                              ],
                                            ))),
                                    Offstage(
                                      offstage: isCheck == true,
                                      child: GestureDetector(
                                          onTap: () {
                                            if (APPLIC.userInfoMap == null) {
                                              Navigator.of(context).push(
                                                  new MaterialPageRoute(
                                                      builder: (context) {
                                                return new WelComePage();
                                              }));
                                              Fluttertoast.showToast(
                                                  msg: "请先登录");
                                              // setState(() {
                                              //   _tabIndex = ins;
                                              // });
                                              return;
                                            }
                                            List<String> temp = new List();
                                            for (int i = 0;
                                                i < gallery.length;
                                                i++) {
                                              temp.add(gallery[i].img);
                                            }
                                            Navigator.of(context).push(
                                                new MaterialPageRoute(
                                                    builder: (context) {
                                              return new ShareGoodsPicPage(
                                                goods_id: widget.goods_id,
                                                pics: temp,
                                                goods_name: goods_name,
                                                price: price,
                                                old_price: old_price,
                                                img: gallery[0].img,
                                              );
                                            }));
                                          },
                                          behavior: HitTestBehavior.opaque,
                                          child: Padding(
                                              padding: EdgeInsets.fromLTRB(
                                                  10, 5, 25, 5),
                                              child: new Column(
                                                children: <Widget>[
                                                  Padding(
                                                    padding: EdgeInsets.all(3),
                                                    child: Image.asset(
                                                        'images/icon_nav_share.png',
                                                        scale: 1.7),
                                                  ),
                                                  Text('分享',
                                                      style: TextStyle(
                                                          fontSize: ScreenUtil
                                                                  .getInstance()
                                                              .setSp(
                                                                  SMALL_FONT_SIZE -
                                                                      4)))
                                                ],
                                              ))),
                                    ),
                                  ],
                                )),
                            Container(
                              height: 10,
                              color: divideColor,
                            ),
                            Container(
                              height: 50,
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: new GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  showGoodsAttributes(context);
                                },
                                child: new Row(
                                  children: <Widget>[
                                    Padding(
                                      padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                      child: Text("商品规格",
                                          style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE - 2),
                                          )),
                                    ),
                                    Expanded(
                                      child: Text(provider.selectedSku ?? '',
                                          style: TextStyle(
                                              color: black_99,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(NORMAL_FONT_SIZE - 5),
                                              fontWeight: FontWeight.w500)),
                                    ),
                                    Icon(
                                      Icons.arrow_forward_ios,
                                      size: 15,
                                    )
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              height: 2,
                              color: divideColor,
                            ),
                            Container(
                              // height: 50,
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: new GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  // showGoodsAttributes(context);
                                },
                                child: new Row(
                                  children: <Widget>[
                                    Padding(
                                      padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                      child: Text("温馨提示",
                                          style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE - 2),
                                          )),
                                    ),
                                    Expanded(
                                      child: Text('$desc',
                                          style: TextStyle(
                                            color: black_99,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE - 5),
                                          )),
                                    ),
                                    // Icon(
                                    //   Icons.arrow_forward_ios,
                                    //   size: 15,
                                    // )
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              height: 2,
                              color: divideColor,
                            ),
                            Container(
                              // height: 50,
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: new GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  // showGoodsAttributes(context);
                                },
                                child: new Row(
                                  children: <Widget>[
                                    Padding(
                                      padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                      child: Text("运费      ",
                                          style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE - 2),
                                          )),
                                    ),
                                    Expanded(
                                      child: Text('$freight',
                                          style: TextStyle(
                                            color: black_99,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE - 5),
                                          )),
                                    ),
                                    // Icon(
                                    //   Icons.arrow_forward_ios,
                                    //   size: 15,
                                    // )
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              height: 10,
                              color: divideColor,
                            ),
                            new Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(150),
                                        0,
                                        20,
                                        0),
                                    height: 1,
                                    color: Colors.grey,
                                  ),
                                ),
                                Text(
                                  "商品详情",
                                  textAlign: TextAlign.right,
                                  style: new TextStyle(
                                      color: Colors.grey, fontSize: 14),
                                ),
                                Expanded(
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        20,
                                        0,
                                        ScreenUtil.getInstance().setWidth(150),
                                        0),
                                    height: 1,
                                    color: Colors.grey,
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              color: white,
                              padding: EdgeInsets.all(10),
                              margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                              child: Html(data: html),
                            )
                          ],
                        ),
                      ),
                    ),
                  )),
                ),
                // Container(
                //   color: white,
                //   padding: EdgeInsets.fromLTRB(20, 5, 20, 20),
                //   child: Row(
                //     crossAxisAlignment: CrossAxisAlignment.center,
                //     mainAxisAlignment: MainAxisAlignment.center,
                //     children: <Widget>[
                //       GestureDetector(
                //         onTap: () {
                //           Navigator.of(context).pop("1");
                //         },
                //         behavior: HitTestBehavior.opaque,
                //         child: new Column(
                //           children: <Widget>[
                //             Padding(
                //               padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                //               child: Image.asset(
                //                 'images/shouye.png',
                //                 width: ScreenUtil.getInstance().setHeight(35),
                //               ),
                //             ),
                //             Text('首页',
                //                 style: TextStyle(
                //                     fontSize: ScreenUtil.getInstance()
                //                         .setSp(SMALL_FONT_SIZE - 4)))
                //           ],
                //         ),
                //       ),
                //       Container(
                //         width: 15,
                //       ),
                //       GestureDetector(
                //         behavior: HitTestBehavior.opaque,
                //         onTap: () {
                //           // showGoodsAttributes(context);
                //           if (APPLIC.userInfoMap == null) {
                //             Navigator.of(context)
                //                 .push(new MaterialPageRoute(builder: (context) {
                //               return new WelComePage();
                //             }));
                //             Fluttertoast.showToast(msg: "请先登录");
                //             // setState(() {
                //             //   _tabIndex = ins;
                //             // });
                //             return;
                //           }
                //           Navigator.of(context)
                //               .push(new MaterialPageRoute(builder: (context) {
                //             return new MyShopCarPage();
                //           }));
                //         },
                //         child: new Column(
                //           children: <Widget>[
                //             Padding(
                //               padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                //               child: Image.asset(
                //                 'images/icon_goodstab_shoppingcart.png',
                //                 width: ScreenUtil.getInstance().setHeight(35),
                //               ),
                //             ),
                //             Text('购物车',
                //                 style: TextStyle(
                //                     fontSize: ScreenUtil.getInstance()
                //                         .setSp(SMALL_FONT_SIZE - 4)))
                //           ],
                //         ),
                //       ),
                //       Container(
                //         width: 15,
                //       ),
                //       GestureDetector(
                //         behavior: HitTestBehavior.opaque,
                //         child: Column(
                //           children: <Widget>[
                //             Image.asset("images/kf.png",
                //                 width: ScreenUtil.getInstance().setHeight(35)),
                //             Text('客服',
                //                 style: TextStyle(
                //                     color: mainColor,
                //                     fontSize:
                //                         ScreenUtil.getInstance().setSp(20)))
                //           ],
                //         ),
                //         onTap: () {
                //           if (APPLIC.userInfoMap == null) {
                //             Fluttertoast.showToast(
                //                 msg: "请先登录", gravity: ToastGravity.CENTER);
                //             Navigator.of(context)
                //                 .push(new MaterialPageRoute(builder: (context) {
                //               return new WelComePage();
                //             }));
                //             return;
                //           }
                //           Navigator.of(context)
                //               .push(new MaterialPageRoute(builder: (context) {
                //             return KeFuTalkPage(
                //                 url:
                //                     "http://kf.0731app.cn/index/index/home?visiter_id=" +
                //                         APPLIC.userInfoMap['user_msg']['uid']
                //                             .toString() +
                //                         "&visiter_name=" +
                //                        "name" +
                //                         "&avatar=" +
                //                         APPLIC.userInfoMap['user_detail']
                //                                 ['avatar']
                //                             .toString() +
                //                         "&business_id=1&groupid=4&special=5");
                //           }));
                //         },
                //       ),
                //       Expanded(
                //         flex: 1,
                //         child: Text(''),
                //       ),
                //       Offstage(
                //         offstage: widget.type != null||widget.zero=='1',
                //         child: new Container(
                //           margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                //           height: ScreenUtil.getInstance().setHeight(55),
                //           decoration: new BoxDecoration(
                //               color: Colors.black54,
                //               borderRadius: BorderRadius.circular(
                //                   ScreenUtil.getInstance().setHeight(10))),
                //           child: new FlatButton(
                //             child: new Padding(
                //               padding: EdgeInsets.all(8.0),
                //               child: new Text(
                //                 "加入购物车",
                //                 style: new TextStyle(
                //                     color: Colors.white,
                //                     fontSize: ScreenUtil.getInstance()
                //                         .setSp(NORMAL_FONT_SIZE - 2)),
                //               ),
                //             ),
                //             onPressed: () {
                //               if (APPLIC.userInfoMap == null) {
                //                 Navigator.of(context).push(
                //                     new MaterialPageRoute(builder: (context) {
                //                   return new WelComePage();
                //                 }));
                //                 Fluttertoast.showToast(msg: "请先登录");
                //                 // setState(() {
                //                 //   _tabIndex = ins;
                //                 // });
                //                 return;
                //               }
                //               // Navigator.of(context).pop();
                //               if (provider.selectedSku.contains("请选择") &&
                //                   hasSku == false) {
                //                 showGoodsAttributes(context);
                //                 return;
                //               }
                //               if (hasSku) {
                //                 addToCar("");
                //                 return;
                //               }
                //               List<Map> skuMap = List();
                //               List<Goods> list = goodsDetailsModel.goods;
                //               for (int i = 0; i < list.length; i++) {
                //                 Map goodsSku = new Map();
                //                 goodsSku['attribute_id'] = list[i].attribute_id;
                //                 goodsSku['value'] = skuProvider
                //                     .selectedSkuModel.sku
                //                     .split(";")[i];
                //                 skuMap.add(goodsSku);
                //               }
                //               addToCar(json.encode(skuMap).toString());
                //             },
                //           ),
                //         ),
                //       ),
                //       // new Container(
                //       //   height: ScreenUtil.getInstance().setHeight(50),
                //       //   decoration: new BoxDecoration(
                //       //       color: Colors.orangeAccent,
                //       //       borderRadius: BorderRadius.circular(
                //       //           ScreenUtil.getInstance().setHeight(50))),
                //       //   child: new FlatButton(
                //       //     child: new Padding(
                //       //       padding: EdgeInsets.all(0.0),
                //       //       child: new Text(
                //       //         "加入购物车",
                //       //         style: new TextStyle(
                //       //             color: Colors.white, fontSize: 14),
                //       //       ),
                //       //     ),
                //       //     onPressed: () {
                //       //       if (APPLIC.userInfoMap == null) {
                //       //         Navigator.of(context).push(
                //       //             new MaterialPageRoute(builder: (context) {
                //       //           return new LoginPage();
                //       //         }));
                //       //         return;
                //       //       }
                //       //       if (APPLIC.userInfoMap['user_msg']['group_id'] ==
                //       //           "1") {
                //       //         Fluttertoast.showToast(msg: "请先升级成店主");
                //       //         return;
                //       //       }
                //       //       if (provider.selectedSku.contains("请选择") &&
                //       //           hasSku == false) {
                //       //         showGoodsAttributes(context);
                //       //       } else {
                //       //         if (hasSku) {
                //       //           addToCar("");
                //       //           return;
                //       //         }
                //       //         List<Map> skuMap = List();
                //       //         List<Goods> list = goodsDetailsModel.goods;
                //       //         for (int i = 0; i < list.length; i++) {
                //       //           Map goodsSku = new Map();
                //       //           goodsSku['attribute_id'] = list[i].attribute_id;
                //       //           goodsSku['value'] =
                //       //               provider.selectedSkuModel.sku.split(";")[i];
                //       //           skuMap.add(goodsSku);
                //       //         }
                //       //         addToCar(json.encode(skuMap).toString());

                //       //         // // print(json.encode(skuMap).toString());
                //       //         // Navigator.of(context)
                //       //         //     .push(MaterialPageRoute(builder: (context) {
                //       //         //   return BuyGoodsPage(
                //       //         //     goods_id: widget.goods_id,
                //       //         //     goods_name: goods_name,
                //       //         //     goods_img: provider.selectedSkuModel.img,
                //       //         //     price: provider.selectedSkuModel.price
                //       //         //         .toString(),
                //       //         //     skuJson: json.encode(skuMap).toString(),
                //       //         //     skuInfo: provider.selectedSkuModel.sku,
                //       //         //   );
                //       //         // }));
                //       //       }
                //       //     },
                //       //   ),
                //       // ),
                //       Container(
                //         width: 10,
                //       ),
                //       new Container(
                //         height: ScreenUtil.getInstance().setHeight(55),
                //         // width: ScreenUtil.getInstance().setWidth(240),
                //         decoration: new BoxDecoration(
                //             gradient: const LinearGradient(
                //                 colors: [mainColor, mainColor]),
                //             borderRadius: BorderRadius.circular(
                //                 ScreenUtil.getInstance().setHeight(10))),
                //         child: new FlatButton(
                //           child: new Padding(
                //             padding: EdgeInsets.all(8.0),
                //             child: new Text(
                //               "立即下单",
                //               style: new TextStyle(
                //                   color: Colors.white,
                //                   fontSize: ScreenUtil.getInstance()
                //                       .setSp(NORMAL_FONT_SIZE - 2)),
                //             ),
                //           ),
                //           onPressed: () {
                //             if (APPLIC.userInfoMap == null) {
                //               Navigator.of(context).push(
                //                   new MaterialPageRoute(builder: (context) {
                //                 return new WelComePage();
                //               }));
                //               return;
                //             }
                //             // if (provider.selectedSku.contains("请选择") &&
                //             //     hasSku == false) {
                //             showGoodsAttributes(context);
                //             // } else {
                //             //   if (hasSku) {
                //             //     Navigator.of(context)
                //             //         .push(MaterialPageRoute(builder: (context) {
                //             //       return BuyGoodsPage(
                //             //         goods_num: goods_num.toString(),
                //             //         goods_id: widget.goods_id,
                //             //         goods_name: goods_name,
                //             //         goods_img: gallery[0].img,
                //             //         type: widget.type.toString(),
                //             //         id: widget.id,
                //             //         price: price.toString(),
                //             //         skuJson: "",
                //             //         skuInfo: "无配置",
                //             //       );
                //             //     }));
                //             //     return;
                //             //   }
                //             // List<Map> skuMap = List();
                //             // List<Goods> list = goodsDetailsModel.goods;
                //             // for (int i = 0; i < list.length; i++) {
                //             //   Map goodsSku = new Map();
                //             //   goodsSku['attribute_id'] = list[i].attribute_id;
                //             //   goodsSku['value'] =
                //             //       provider.selectedSkuModel.sku.split(";")[i];
                //             //   skuMap.add(goodsSku);
                //             // }
                //             // // print(json.encode(skuMap).toString());
                //             // Navigator.of(context)
                //             //     .push(MaterialPageRoute(builder: (context) {
                //             //   return BuyGoodsPage(
                //             //     goods_num: goods_num.toString(),
                //             //     type: widget.type.toString(),
                //             //     goods_id: widget.goods_id,
                //             //     goods_name: goods_name,
                //             //     id: widget.id,
                //             //     goods_img: provider.selectedSkuModel.img,
                //             //     price: provider.selectedSkuModel.price
                //             //         .toString(),
                //             //     skuJson: json.encode(skuMap).toString(),
                //             //     skuInfo: provider.selectedSkuModel.sku,
                //             //   );
                //             // }));
                //             // }
                //           },
                //         ),
                //       )
                //     ],
                //   ),
                // )
              ],
            );
          })),
    );
  }

  showGoodsAttributes(BuildContext context) {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (BuildContext context, setState) {
              return new Container(
                height: MediaQuery.of(context).size.height * 3 / 4,
                alignment: AlignmentDirectional.center,
                padding: EdgeInsets.fromLTRB(20, 0, 10, 10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(15),
                      topRight: Radius.circular(15),
                    ),
                    color: white),
                child: new Column(
                  children: <Widget>[
                    new Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Container(
                            width: 50,
                            color: white,
                            height: 50,
                            child: Image.asset('images/icon_close.png'),
                          ),
                        )
                      ],
                    ),
                    Expanded(
                      flex: 1,
                      child: SingleChildScrollView(
                        child: ChangeNotifierProvider.value(
                            value: skuProvider,
                            child: SkuDialog(
                              goods_name: goods_name,
                              initPrice: price.toString(),
                              img: gallery[0].img,
                            )),
                      ),
                    ),
                    // Row(
                    //   children: <Widget>[
                    //     Expanded(
                    //       flex: 3,
                    //       child: Text('数量',
                    //           maxLines: 1,
                    //           style: TextStyle(
                    //               fontSize: ScreenUtil.getInstance()
                    //                   .setSp(SMALL_FONT_SIZE),
                    //               color: black)),
                    //     ),
                    //     GestureDetector(
                    //       child: Icon(
                    //         Icons.remove,
                    //         color: black,
                    //         size: ScreenUtil.getInstance().setHeight(DP_30 + 5),
                    //       ),
                    //       onTap: () {
                    //         if (goods_num == 1) {
                    //           return;
                    //         }
                    //         goods_num--;
                    //         setState(() {});
                    //       },
                    //     ),
                    //     Container(
                    //       decoration: BoxDecoration(
                    //           borderRadius: BorderRadius.circular(2),
                    //           color: f0Color),
                    //       padding: EdgeInsets.fromLTRB(
                    //           ScreenUtil.getInstance().setHeight(DP_20),
                    //           2,
                    //           ScreenUtil.getInstance().setHeight(DP_20),
                    //           2),
                    //       margin: EdgeInsets.fromLTRB(
                    //           ScreenUtil.getInstance().setHeight(DP_10),
                    //           0,
                    //           ScreenUtil.getInstance().setHeight(DP_10),
                    //           0),
                    //       child: Text(
                    //         goods_num.toString(),
                    //         style: TextStyle(
                    //             fontSize: ScreenUtil.getInstance()
                    //                 .setSp(SMALL_FONT_SIZE),
                    //             color: Colors.black87),
                    //       ),
                    //     ),
                    //     GestureDetector(
                    //       child: Icon(
                    //         Icons.add,
                    //         size: ScreenUtil.getInstance().setHeight(DP_30 + 5),
                    //         color: black,
                    //       ),
                    //       onTap: () {
                    //         if (goods_num >=
                    //             int.parse(skuProvider.selectedSkuModel.inventory
                    //                 .toString())) {
                    //           Fluttertoast.showToast(msg: "超出库存数量");
                    //           return;
                    //         }
                    //         goods_num++;
                    //         setState(() {});
                    //       },
                    //     ),
                    //     Expanded(child: Center()),
                    //   ],
                    // ),
                    // Container(
                    //   height: 20,
                    // ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        // Offstage(
                        //   offstage: widget.type != null||widget.zero=='1',
                        //   child: new Container(
                        //     margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                        //     height: ScreenUtil.getInstance().setHeight(55),
                        //     width: ScreenUtil.getInstance().setWidth(220),
                        //     decoration: new BoxDecoration(
                        //         color: Colors.black54,
                        //         borderRadius: BorderRadius.circular(
                        //             ScreenUtil.getInstance().setHeight(10))),
                        //     child: new FlatButton(
                        //       child: new Padding(
                        //         padding: EdgeInsets.all(8.0),
                        //         child: new Text(
                        //           "加入购物车",
                        //           style: new TextStyle(
                        //               color: Colors.white,
                        //               fontSize: ScreenUtil.getInstance()
                        //                   .setSp(NORMAL_FONT_SIZE)),
                        //         ),
                        //       ),
                        //       onPressed: () {
                        //         // Navigator.of(context).pop();
                        //         if (hasSku) {
                        //           addToCar("");
                        //           return;
                        //         }
                        //         if (skuProvider.selectedSku.contains("请选择")) {
                        //           Fluttertoast.showToast(
                        //               msg: skuProvider.selectedSku);
                        //           return;
                        //         }
                        //         List<Map> skuMap = List();
                        //         List<Goods> list = goodsDetailsModel.goods;
                        //         for (int i = 0; i < list.length; i++) {
                        //           Map goodsSku = new Map();
                        //           goodsSku['attribute_id'] =
                        //               list[i].attribute_id;
                        //           goodsSku['value'] = skuProvider
                        //               .selectedSkuModel.sku
                        //               .split(";")[i];
                        //           skuMap.add(goodsSku);
                        //         }
                        //         addToCar(json.encode(skuMap).toString());
                        //       },
                        //     ),
                        //   ),
                        // ),
                        new Container(
                          height: ScreenUtil.getInstance().setHeight(55),
                          width: ScreenUtil.getInstance().setWidth(220),
                          margin: EdgeInsets.fromLTRB(20, 10, 0, 10),
                          decoration: new BoxDecoration(
                            color:mainColor,
                              borderRadius: BorderRadius.circular(
                                  ScreenUtil.getInstance().setHeight(10))),
                          child: new FlatButton(
                            child: new Padding(
                              padding: EdgeInsets.all(8.0),
                              child: new Text(
                                "确定选择",
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE)),
                              ),
                            ),
                            onPressed: () {
                              if (APPLIC.userInfoMap == null) {
                                Navigator.of(context).push(
                                    new MaterialPageRoute(builder: (context) {
                                  return new WelComePage();
                                }));
                                return;
                              }
                              // if (APPLIC.userInfoMap == null ||
                              //     APPLIC.userInfoMap['user_msg']['group_id']
                              //             .toString() ==
                              //         "1") {
                              //   Navigator.of(context).push(
                              //       new MaterialPageRoute(builder: (context) {
                              //     return new VIPTestPage();
                              //   }));
                              //   return;
                              // }
                              if (hasSku) {
                                return;
                              }
                              if (skuProvider.selectedSku.contains("请选择")) {
                                Fluttertoast.showToast(
                                    msg: skuProvider.selectedSku);
                                return;
                              }
                              List<Map> skuMap = List();
                              List<Goods> list = goodsDetailsModel.goods;
                              for (int i = 0; i < list.length; i++) {
                                Map goodsSku = new Map();
                                goodsSku['attribute_id'] = list[i].attribute_id;
                                goodsSku['value'] = skuProvider
                                    .selectedSkuModel.sku
                                    .split(";")[i];
                                skuMap.add(goodsSku);
                              }
                              Navigator.of(context)
                                  .pop();

                              Navigator.of(context)
                                  .pop(json.encode(skuMap).toString());
                            },
                          ),
                        )
                      ],
                    ),
                    Container(
                      height: 30,
                    ),
                  ],
                ),
              );
            },
          );
        });
  }

  addToCar(String attr) async {
    Map map = new Map();
    map['token'] = token;
    map['goods_id'] = widget.goods_id;
    map['sign_type'] = SignType.ADD_SHOP_CAR;
    map['goods_num'] = goods_num;
    if (attr != "") map['goods_sku'] = attr;
    Response<String> response =
        await HttpUtil().post(Api.ADD_SHOP_CAR, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    Fluttertoast.showToast(msg: userMap['msg']);
    if (code == 1 && mounted) {
      APPLIC.eventBus.fire(ShopCarEvent());
    }
  }
}
